# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -*- coding: utf-8 -*-

import requests
import json
# import cv2
import base64
import os, sys
import time
from pdf_png import pdf_png
import io


def cv2_to_base64(image):
    #data = cv2.imencode('.jpg', image)[1]
    return base64.b64encode(image).decode('utf8')  #data.tostring()).decode('utf8')

def content(input_image):
    headers = {"Content-type": "application/json"}
    url = "http://127.0.0.1:8002/ocr/prediction"
   

    dic_content = {}
    for i,img in enumerate(input_image) :

        imgByteArr = io.BytesIO()
        img.save(imgByteArr, format='JPEG')
        imgByteArr = imgByteArr.getvalue()
        image = cv2_to_base64(imgByteArr)
        data = {"key":["image"],"value":[image]}

        requests.DEFAULT_RETRIES = 5  # 增加重试连接次数
        s = requests.session()
        s.keep_alive = False  # 关闭多余连接
        
        r = requests.post(url=url, headers=headers, data=json.dumps(data))

        dic_content[i] = eval((r.json().get('value'))[0])
        # list_content.append((r.json().get('value'))[0])
    return dic_content





